﻿using Caliburn.Micro;
using DataAccess.Toolkit.Services;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Linq;
using System.Windows;
using UI.Toolkit.ViewModels;

namespace UI.Toolkit
{
    public class Bootstrapper : BootstrapperBase
    {

        private CompositionContainer _container;

        #region Constructor
        public Bootstrapper()
        {
            Initialize();
        }
        #endregion

        #region Overrides
        /// <summary>
        /// 用于配置IOC容器
        /// </summary>
        protected override void Configure()
        {
            var catalog = new AggregateCatalog(
            new AggregateCatalog(AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>())
             );
            _container = new CompositionContainer(catalog);
            var batch = new CompositionBatch();

            batch.AddExportedValue<IWindowManager>(new WindowManager());
            batch.AddExportedValue<IEventAggregator>(new EventAggregator());
            batch.AddExportedValue<ICustomerServices>(new CustomerServices());
            batch.AddExportedValue(_container);

            _container.Compose(batch);

        }


        /// <summary>
        /// IOC容器获取实例的方法
        /// </summary>
        /// <param name="serviceType"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        protected override object GetInstance(Type serviceType, string key)
        {
            var contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(serviceType) : key;
            var exports = _container.GetExportedValues<object>(contract);
            if (exports.Any())
            {
                return exports.First();
            }
            throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
        }
        /// <summary>
        /// IOC容器获取所有实例的方法
        /// </summary>
        /// <param name="serviceType"></param>
        /// <returns></returns>
        protected override IEnumerable<object> GetAllInstances(Type serviceType)
        {
            string contractName = AttributedModelServices.GetContractName(serviceType);

            var exports = _container.GetExportedValues<object>(contractName);

            return exports;
        }

        /// <summary>
        /// IOC容器注入实例的方法
        /// </summary>
        /// <param name="instance"></param>
        protected override void BuildUp(object instance)
        {
            _container.SatisfyImportsOnce(instance);
        }

        protected override void OnStartup(object sender, StartupEventArgs e)
        {
            DisplayRootViewForAsync<ShellViewModel>();
        }

        #endregion
    }
}
